/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Keshav
 */
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jibble.pircbot.*;
import com.google.api.*;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.json.*;
import org.json.simple.parser.JSONParser;


public class JavaBot extends PircBot {

    private static final String REFERRER_PATH = System.getProperty("user.home") + "/.gtReferrer";

    public JavaBot() {
        this.setName("MyBot");
        try {
            initTranslate();
        } catch (IOException ex) {
            Logger.getLogger(JavaBot.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void initTranslate() throws IOException {
        Translate.setHttpReferrer("http://google.com");
    }

    public void onMessage(String channel, String sender,
            String login, String hostname, String message) {
        if (message.startsWith("!time")) {
            String time = new java.util.Date().toString();
            sendMessage(channel, sender + ":");
        } else if (message.startsWith("!google")) {
            sendMessage(channel, sender + ":");
        } else if (message.startsWith("!translate")) {
            System.out.println("Received private msg");

            String command = message.split(" ", 2)[0];
            String text = message.split(" ", 2)[1];

            sendMessage(channel, sender + ": " + translate(text));
        } else if (message.startsWith("!wiki")) {
            sendMessage(channel, sender + ":");
        } else if (message.startsWith("!imdb")) {
            sendMessage(channel, sender + ":");
        } else if (message.startsWith("!youtube")) {
            sendMessage(channel, sender + ":");
        } else if (message.startsWith("!stocks")) {
            sendMessage(channel, sender + ": " + stock(message));
        } else if (message.startsWith("!currency")) {
            sendMessage(channel, sender + ": " + currency(message));
        } else if (message.startsWith("!help")) {
            sendMessage(channel, sender + ":");
        }
    }

    private String translate(String message) {
        String[] inputs = message.split(" ", 3);

        String fromLang = inputs[0];
        String toLang = inputs[1];

        Translate.setHttpReferrer("http://google.com");

        String translated;
        try {
            translated = Translate.execute(inputs[2], Language.fromString(fromLang), Language.fromString(toLang));

            return translated;
        } catch (Exception ex) {
            return "Could not translate!";
        }
    }

    private String stock(String message) {
        try {
            String stockNames[] = message.split(" ");
            String concat = "";
            for (int i = 1; i < stockNames.length - 1; i++) {
                concat += stockNames[i] + "+";
            }
            concat += stockNames[stockNames.length - 1];
            String urlString = "http://download.finance.yahoo.com/d/quotes.csv?s=" + concat + "&f=l";
            URL url = new URL(urlString);
            URLConnection urlCon = url.openConnection();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    urlCon.getInputStream()));
            String inputLine;
            ArrayList<String> vals = new ArrayList<String>();
            int count = 1;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                String price = "";
                if (inputLine.startsWith("\"N/A")) {
                    price = "N/A";
                } else {
                    price = "$" + inputLine.split("-")[1].replaceAll("\\<.*?>", "").trim();
                }
                price = price.replace("\"", "");
                String text = stockNames[count].toUpperCase() + " - " + price.trim() + " ";
                System.out.println(text);
                vals.add(text);
                count++;
            }
            in.close();
            concat = "";
            for (String s : vals) {
                concat += s + "   ";
            }
            return concat;
        } catch (IOException ex) {
            return "Could not find stocks!";
        }
    }

    private String currency(String message){
        try {
            String[] args = message.split(" ");
            String num = args[1];
            String from = args[2];
            String to = args[3];
            String urlString = "http://www.google.com/ig/calculator?hl=en&q=" + num + from + "%3D%3F" + to;
            URL url = new URL(urlString);
            URLConnection urlCon = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
            String inputLine, retString = null;
            while ((inputLine = in.readLine()) != null) {
                retString = inputLine;
                break;
            }

            JSONObject obj = new JSONObject(retString);
            String lhs = (String) obj.get("lhs");
            String rhs = (String) obj.get("rhs");
            System.out.println("l: " + lhs + "  r: " + rhs);
            if(lhs == "" || rhs == ""){
                return "Incorrect currency types";
            } else {
                return lhs + " is equal to " + rhs;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return "Could not convert currency!";
        }
    }
}
